<template>
    <div>
        <el-steps style="min-width: 1200px;" :active="step" align-center>
            <el-step title="基本信息"/>
            <el-step title="上传图片"/>
            <el-step title="上传视频"/>
            <el-step title="参数确认"/>
            <el-step title="等待审核" />
        </el-steps>
    </div>

    <div style="height: 65vh;min-width: 1200px;">
        <div v-if="step===0" class="basicInfo">
            <el-form :model="createVideo" label-width="auto" style="max-width: 600px">
                <el-form-item label="视频标题">
                    <el-input v-model="createVideo.title" style="width: 340px;" placeholder="Please input" />
                </el-form-item>

                <el-form-item label="视频类型">
                    <el-radio-group v-model="createVideo.typeName">
                        <el-radio value="游戏">游戏</el-radio>
                        <el-radio value="二次元">二次元</el-radio>
                        <el-radio value="音乐">音乐</el-radio>
                        <el-radio value="美食">美食</el-radio>
                        <el-radio value="知识">知识</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
           
        </div>

        <div v-else-if="step===1" class="upload">
            <h1>上传一张封面图片</h1>
            <div>
                <el-upload
                    class="avatar-uploader"
                    :show-file-list="false"
                    :before-upload="beforeAvatarUpload"
                >
                    <img v-if="createVideo.imageUrl" :src="address.minioUrl+'image/'+createVideo.imageUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
                
            </div>
            
        </div>

        <div v-else-if="step===2">
            <el-upload
                ref="upload"
                class="upload"
                :limit="1"
                :on-exceed="handleExceed"
                :auto-upload="false"
                :before-upload="handleBeforeUpload"
            >
                <template #trigger>
                    <el-button type="primary">选择一个文件</el-button>
                </template>
                <el-button style="margin-left: 10px;" type="success" @click="submitUpload" :disabled="buttonDisable">开始上传</el-button>
                <template #tip>
                    <div style="color: red;font-size: 12px;margin-top: 8px;">请勿超过200MB</div>
                </template>
            </el-upload>

            <div style="width: 100vh;margin-left: 20%;">
                <el-progress :text-inside="true" :stroke-width="26" :percentage=progress style="margin-top: 20px;" />
                <div style="text-align: center;margin-top: 10px;">
                    <el-text style="color: rgb(99, 206, 255);">{{status}}</el-text>
                    <el-text v-if="status=='正在上传'" style="color: rgb(99, 206, 255);"> - {{uploadSpeed.toFixed(2)}}KB/s</el-text>
                </div>
            </div>
        </div>


        <div v-else-if="step===3">
            <div style="text-align: center;">
                <h1>确认信息</h1>
                <h3>标题：{{createVideo.title}}</h3>
                <h3>类型：{{createVideo.typeName}}</h3>
                <h3>视频预览：</h3>
            </div>
        </div>

        <div v-else-if="step===4">
            <div style="text-align: center;">
                <h1>您的作品已经加入审核队列</h1>
                <h3>请耐心等待审核完成</h3>
            </div>
        </div>
    </div>

    <div style="text-align: center;">
            <el-button v-if="step<4" :disabled="step<=0 || buttonDisable"  @click="nextStep(-1)">上一步</el-button>
            <el-button v-else @click="$router.push('/author/reviewing')">查看审核列表</el-button>
            <el-button  v-if="step<3" :disabled="rule() || buttonDisable" @click="nextStep(1)">下一步</el-button>
            <el-button v-else-if="step===3" :disabled="buttonDisable" @click="ToExamine()">申请审核</el-button>
    </div>


</template>

<script setup lang="ts">
    import { ref } from 'vue';
    import CreateVideo from "@/types/author/CreateVideo";
    import { ElMessage,UploadInstance,UploadProps, UploadRawFile,genFileId  } from 'element-plus';
    import UseUploadVideo from '@/utils/uploadVideo'
    import { getUploadFileMD5 } from '@/utils/getFileMd5';
    import request from '@/base/request';
    import {address} from '@/base/address';
    const buttonDisable=ref(false);
    const {uploadVideo,progress,status,uploadSpeed} = UseUploadVideo();
    const upload = ref<UploadInstance>()
    const step = ref(0);
    const createVideo = ref<CreateVideo>({
        title: "",
        typeName: "",
        videoMd5:"",
        imageUrl:""
    });


    const beforeAvatarUpload=async (file)=>{
        
        if (file.size > 10 * 1024 * 1024) {
            ElMessage.error("文件过大，请选择10MB以下的文件");
            return false;
        }

        const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
        if (!allowedTypes.includes(file.type)) {
            ElMessage.error("文件格式不支持，请上传jpg, png或gif格式的图片");
            return false;
        }
        buttonDisable.value=true;
        const formData = new FormData()
        formData.append("file",file);

        const response = (await request.post("/video/videoBaseInfo/uploadImage",formData)).data
        if(response.code==200){
            createVideo.value.imageUrl=response.data;
        }else{
            ElMessage.error(response.msg)
        }
        buttonDisable.value=false;
        return false;
    }

    // 上传文件数量超出（即自动覆盖文件）
    const handleExceed: UploadProps['onExceed'] = (files) => {
        upload.value!.clearFiles()
        const file = files[0] as UploadRawFile
        file.uid = genFileId()
        upload.value!.handleStart(file)
    }

    const nextStep = (i) => {
        if (step.value==0 && !createVideo.value.title || !createVideo.value.typeName) {
            ElMessage.error("请填写完整信息");
            return;
        }
        step.value=Math.max(0, step.value+i);
    };

    const rule = ()=>{
        if (step.value==0 && !createVideo.value.title || !createVideo.value.typeName)return true;
        if((step.value==1 && createVideo.value.imageUrl=='') || (step.value===2 && createVideo.value.videoMd5==''))return true;
        return false;
    }


    const submitUpload = () => {
        upload.value?.submit()
    }

    const handleBeforeUpload= async (file)=>{
        if (file.size > 1024 * 1024 * 1024) {
            ElMessage.error("文件过大，请选择1G以下的文件");
            return false;
        }


        const allowedTypes = ['video/mp4', 'video/avi', 'video/mpeg','video/m3u8'];
        if (!allowedTypes.includes(file.type)) {
            ElMessage.error("文件格式不支持，请上传mp4, avi, mpeg或m3u8格式的视频");
            return false;
        }
        buttonDisable.value=true;
        progress.value=0;
        status.value="正在解析文件";
        let result;
        let fileMd5;
        try{
            fileMd5=await getUploadFileMD5(file);
            status.value="等待上传"
            result=await uploadVideo(file,fileMd5)
        }catch(e){
            buttonDisable.value=false;
            status.value="上传失败"
        }

        if(result){
            ElMessage.success("上传成功")
            createVideo.value.videoMd5=fileMd5;
        }
        buttonDisable.value=false;
        return false;
    }

    const ToExamine = async ()=>{
        buttonDisable.value=true;
        const response=(await request.post("/video/review/createVideo",createVideo.value)).data
        if(response.code==200){
            ElMessage.success("提交成功")
            step.value++;
        }else{
            ElMessage.error(response.message)
        }
        buttonDisable.value=false;
    }

    

    
</script>

<style scoped>
    .basicInfo {
        margin-left: 35%;
        margin-top: 30px;
    }

    .upload{
        margin-top: 30px;
        text-align: center;
    }
    .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>


<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>